import store from '../store'

export function serialize (obj) {
  const s = []

  for (const item in obj) {
    const k = encodeURIComponent(item)
    const v = encodeURIComponent(obj[item] == null ? '' : obj[item])
    s.push(`${k}=${v}`)
  }

  return s.join('&')
}

export function queryParse (url) {
  const qs = {}
  if (!url) {
    url = window.location.href
  }
  url.replace(/([^?=&#]+)(=([^&#]*))?/g, ($0, $1, $2, $3) => {
    /* istanbul ignore next */
    if ($3 === undefined) {
      return
    }
    qs[$1] = decodeURIComponent($3)
  })
  return qs
}

export function mergeQueryString (url, newQueryStringObj) {
  if (!url) return ''
  if (!newQueryStringObj) return url

  const currentQueryStringObj = queryParse(url)
  const queryStringObj = Object.assign({},
    currentQueryStringObj,
    newQueryStringObj)
  const queryString = serialize(queryStringObj)
  return queryString
    ? url.split('?')[0] + '?' + serialize(queryStringObj)
    : url.split('?')[0]
}

export function getEnv () {
  const {
    hostname,
  } = window.location

  if (/^192\.168\./.test(hostname) || hostname === 'localhost') {
    return 'local'
  } else {
    return 'prod'
  }
}


export function countForShow(count) {
  if (count > 100000000) {
    return (count / 100000000).toFixed(2) + '亿'
  } else if (count > 10000) {
    return (count / 10000).toFixed(1) + '万'
  } else {
    return count;
  }
}

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if ((`${time}`).length === 10) time = parseInt(time, 10) * 1000;
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1];
    if (result.length > 0 && value < 10) {
      value = `0${value}`;
    }
    return value || 0;
  });
  return timeStr;
}

export function setToken(token) {
  console.log(token)
  store.commit('GET_TOKEN', token)
  console.log(store.state.token)
}

export function resetToken(token) {
  store.commit('GET_TOKEN', token)
  // window.location.reload()
}

export function networkError() {
  console.log('error')
}